<?php

namespace stlswm\DouyinOpenApi\pay\ecpay;

class Sign
{
    private static function isArrMap($map): bool
    {
        foreach ($map as $k => $v) {
            if (is_string($k)) {
                return true;
            }
        }

        return false;
    }

    private static function arrayToStr($map): string
    {
        $isMap = self::isArrMap($map);

        $result = "";
        if ($isMap) {
            $result = "map[";
        }

        $keyArr = array_keys($map);
        if ($isMap) {
            sort($keyArr);
        }

        $paramsArr = [];
        foreach ($keyArr as $k) {
            $v = $map[$k];
            if ($isMap) {
                if (is_array($v)) {
                    $paramsArr[] = sprintf("%s:%s", $k, self::arrayToStr($v));
                } else {
                    $paramsArr[] = sprintf("%s:%s", $k, trim(strval($v)));
                }
            } else {
                if (is_array($v)) {
                    $paramsArr[] = self::arrayToStr($v);
                } else {
                    $paramsArr[] = trim(strval($v));
                }
            }
        }

        $result = sprintf("%s%s", $result, join(" ", $paramsArr));
        if (!$isMap) {
            $result = sprintf("[%s]", $result);
        } else {
            $result = sprintf("%s]", $result);
        }

        return $result;
    }

    /**
     * @param  string  $salt
     * @param  array   $map
     * @return string
     */
    public static function sign(string $salt, array $map): string
    {
        $rList = [];
        foreach ($map as $k => $v) {
            if ($k == "other_settle_params" || $k == "app_id" || $k == "sign" || $k == "thirdparty_id") {
                continue;
            }

            $value = trim(strval($v));
            if (is_array($v)) {
                $value = self::arrayToStr($v);
            }

            $len = strlen($value);
            if ($len > 1 && substr($value, 0, 1) == "\"" && substr($value, $len - 1) == "\"") {
                $value = substr($value, 1, $len - 1);
            }
            $value = trim($value);
            if ($value == "" || $value == "null") {
                continue;
            }
            $rList[] = $value;
        }
        $rList[] = $salt;
        sort($rList, SORT_STRING);
        return md5(implode('&', $rList));
    }
}